﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.IO;

namespace Workshop
{
    public partial class FormITgroups : Form
    {
        public FormITgroups()
        {
            InitializeComponent();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void cbInstructor_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void FormITgroups_Load(object sender, EventArgs e)
        {
            lbltip1.Hide();
            lbltip2.Hide();
            if (File.Exists("Staff.xml"))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Staff.xml");
                string path = "//InstructorID[@Name]";
                XmlNodeList nodelist = doc.SelectNodes(path);
                DataTable dt = new DataTable();
                DataColumn dc1 = new DataColumn("Name", typeof(String));
                DataColumn dc9 = new DataColumn("ID");
                dt.Columns.Add(dc1);
                dt.Columns.Add(dc9);

                if (nodelist != null)
                {
                    for(int i =0; i<nodelist.Count;i++)
                    {
                        dt.Rows.Add(nodelist[i].Attributes[0].Value,nodelist[i].InnerText);
                    }
                }
                cbInstructor.DataSource = dt;
                cbInstructor.DisplayMember = dt.Columns[0].ColumnName;
                cbInstructor.ValueMember = dt.Columns[1].ColumnName;

            }
           
            dt2.Columns.Add(dc2);
            dt2.Columns.Add(dc3);
            dt3.Columns.Add(dc4);
            dt3.Columns.Add(dc5);
            dgv1.DataSource = dt2;
            dgv2.DataSource = dt3;

            //txtChange.Text = remain.ToString();
            remain = getremain();
            lblRemain.Text = remain.ToString();
           
            XmlDocument doc2 = new XmlDocument();
                doc2.Load("Course.xml");
                string pathTotal = "//Courses/ITCourse";
                XmlNode node = doc2.SelectSingleNode(pathTotal);
                label5.Text = node.Attributes[0].Value;
            txtChange.Text = node.Attributes[0].Value;

        }
        
        /*gobal varibles*/
        DataTable dt2 = new DataTable();
        DataColumn dc2 = new DataColumn("name", typeof(String));
        DataColumn dc3 = new DataColumn("itgroups", typeof(String));
        DataTable dt3 = new DataTable();
        DataColumn dc4 = new DataColumn("name", typeof(String));
        DataColumn dc5 = new DataColumn("workload", typeof(String));
        int groups=-1;
        int group_selected;
        int remain = 0;
       string id = null;
        double workload = -1;
        static public int counter = 0;


        private void button1_Click(object sender, EventArgs e)
        {
            FormAddIT.i = 0;
            int te;
            if (txtChange.Text.Trim() != String.Empty)
            {
                
                if (txtITGroups.Text.Trim()!=String.Empty)
                {
                    //int remainGroup;
                    //int.TryParse(lblRemain.Text, out remainGroup);
                    if (int.TryParse(txtITGroups.Text, out te))
                    {
                        string name = null;
                        int j = 0;
                        Boolean inputornot = true;
                        int numberGroup;
                        int.TryParse(txtITGroups.Text, out numberGroup);
                        int origin = checkforgroup(cbInstructor.SelectedValue.ToString());
                        if (numberGroup - origin <= getremain())
                            {

                                XmlDocument docsearch = new XmlDocument();
                                docsearch.Load("Staff.xml");
                                string pathsearch = "//InstructorID";
                                XmlNodeList nodesearch = docsearch.SelectNodes(pathsearch);
                                for (int i = 0; i < nodesearch.Count; i++)
                                {
                                    if (nodesearch[i].InnerText == cbInstructor.SelectedValue.ToString())
                                    {
                                        name = nodesearch[i].Attributes[0].Value;
                                        double.TryParse(nodesearch[i].Attributes[1].Value, out workload);
                                        break;
                                    }
                                }
                                    remain = getremain();
                                    int.TryParse(txtITGroups.Text, out group_selected);
                                    id = cbInstructor.SelectedValue.ToString();
                            if (checkfornew(cbInstructor.SelectedValue.ToString()) == true)
                            {
                                if (checkforta(cbInstructor.SelectedValue.ToString()) == true)
                                {
                                    MessageBox.Show("The IT courses of this instructor has been assigned Ta, so you can not modify it until delete the Ta!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                    return;
                                }
                                MessageBox.Show("This operation will change the assigned arrangement of this instructor ", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            for (int i = 0; i < group_selected; i++)
                            {
                                if (!addstudent(name))
                                {
                                    inputornot = false;
                                    break;
                                }

                            }

                            if ((inputornot&&counter==group_selected)||group_selected==0)
                            {
                                if (checkfornew(cbInstructor.SelectedValue.ToString()) == true)
                                {
                                    //MessageBox.Show("This operation will change the assigned arrangement of this instructor ");
                                    clear();
                                    int origingroups = checkforgroup(cbInstructor.SelectedValue.ToString());

                                    remain = remain + origingroups;
                                    workload = workload - (origingroups - 1) * 0.5 - 1;
                                    deleteIT(cbInstructor.SelectedValue.ToString(), origingroups);
                                    deleteitgroup(cbInstructor.SelectedValue.ToString());
                                }
                                //id = cbInstructor.SelectedValue.ToString();
                                //int.TryParse(txtITGroups.Text, out group_selected);
                                remain = remain - group_selected;
                                if (remain >= 0)
                                {
                                    if (group_selected > 0)
                                    {
                                        workload = workload + (group_selected - 1) * 0.5 + 1;
                                    }
                                    else
                                    {
                                        workload = 0;
                                    }
                                    if (workload >= 3)
                                    {
                                        MessageBox.Show("This instructor already has three workload!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }

                                    string testname = null;

                                    XmlDocument doc = new XmlDocument();
                                    doc.Load("Course.xml");
                                    string path = "//ITCourse/InstructorID";
                                    XmlNodeList nodelist = doc.SelectNodes(path);


                                    for (j = 0; j < nodelist.Count; j++)
                                    {
                                        if (nodelist[j].InnerText == id)
                                        {
                                            nodelist[j].Attributes[1].Value = txtITGroups.Text;
                                            testname = nodelist[j].Attributes[0].Value;
                                            doc.Save("Course.xml");
                                            break;
                                        }
                                    }

                                    if (testname == null)
                                    {
                                        if (txtITGroups.Text != "0")
                                        {
                                            string path1 = "//Courses/ITCourse";
                                            //MessageBox.Show("no exist");
                                            appendnode(path1, name, txtITGroups.Text, id);
                                        }
                                    }
                                    //nodelist[j].Attributes[1].Value = txtITGroups.Text;
                                    //node.Attributes[1].Value = txtITGroups.Text;
                                    //doc.Save("Course.xml");

                                    FormAddIT frm2 = new FormAddIT();
                                        frm2.putintoxml(group_selected);

                                    XmlDocument docworkload = new XmlDocument();
                                    docworkload.Load("Staff.xml");
                                    string pathworkload = "//Instructors/InstructorID";
                                    XmlNodeList nodelistworkload = docworkload.SelectNodes(pathworkload);
                                    for (int i = 0; i < nodelistworkload.Count; i++)
                                    {
                                        if (nodelistworkload[i].InnerText == id)
                                        {
                                            nodelistworkload[i].Attributes[1].Value = workload.ToString();
                                            break;
                                        }
                                    }
                                    docworkload.Save("Staff.xml");

                                    saveremain(remain);

                                    lblRemain.Text = remain.ToString();
                                    //lbltest.Text = cbInstructor.SelectedValue + txtITGroups.Text;
                                    dt2.Rows.Add(name, txtITGroups.Text);
                                    dgv1.DataSource = dt2;
                                    dt3.Rows.Add(name, workload);
                                    dgv2.DataSource = dt3;
                                }


                                else
                                {
                                    MessageBox.Show("There is no enough groups to be assigned!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                }
                            }
                            else
                            {
                                MessageBox.Show("Operation failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                txtITGroups.Text = null;
                            }

                        }
                        else
                        {
                            MessageBox.Show("There is no enough group to be assigned!");
                        }
                    }
                    else MessageBox.Show("Please input real number!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }
                else
                {
                    MessageBox.Show("Please input the amount of IT Groups assigned to this introductor!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("Please input the total number of groups!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
        }

        private Boolean checkforta(String id)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNodeList nodeList = doc.SelectNodes("//Courses/CourseInfo/Course");
            for(int i = 0; i < nodeList.Count; i++)
            {
                if(nodeList[i].ChildNodes[6].InnerText == id && nodeList[i].ChildNodes[7].InnerText == "IT")
                {
                    if (nodeList[i].ChildNodes[4].InnerText != "" || nodeList[i].ChildNodes[5].InnerText != "") return true;
                }
            }
            return false;
        }

        private void appendnode(string path,string name,string groups,string id)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNode parent = doc.SelectSingleNode(path);
            XmlNode newnode = doc.CreateElement("InstructorID");
            newnode.Attributes.Append(CreateAttribute(parent, "Name", name));
            newnode.Attributes.Append(CreateAttribute(parent, "Group", groups));
            newnode.InnerText = id;
            parent.AppendChild(newnode);
            doc.Save("Course.xml");
        }

        private void saveremain(int re)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNode node = doc.SelectSingleNode("//Courses/ITCourse");
            //int.TryParse(node.Attributes[1].Value, out g);
            node.Attributes[1].Value = re.ToString();
            doc.Save("Course.xml");
        }

        private int getremain()
        {
            int g;
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNode node = doc.SelectSingleNode("//Courses/ITCourse");
            int.TryParse(node.Attributes[1].Value,out g);
            return g;
        }

        private Boolean checkfornew(String id)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNodeList nodelist = doc.SelectNodes("//Courses/ITCourse/InstructorID");
            if (nodelist == null) return false;
            for (int i = 0; i < nodelist.Count; i++)
            {
                if (nodelist[i].InnerText == id)
                {
                    return true;
                }
                //else return false;
            }
            return false;
        }

        private Boolean addstudent(String name)
        {
            FormAddIT form2 = new FormAddIT(name,id,group_selected);

            form2.ShowDialog();
            //Form fm2 = new FormAddIT();

            return form2.Waitforfinish();
            //form2.ShowDialog();
        }
           
        private int checkforgroup(String id)
        {
            int g = 0;
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNodeList nodelist = doc.SelectNodes("//ITCourse/InstructorID");
            for (int i = 0; i < nodelist.Count; i++)
            {
                if (nodelist[i].InnerText == id)
                {
                    int.TryParse(nodelist[i].Attributes[1].Value, out g);
                    return g;
                }
            }
            return 0;
        }
    
           

        public XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value)
        {
            try
            {
                XmlDocument doc = node.OwnerDocument;
                XmlAttribute attr = null;
                attr = doc.CreateAttribute(attributeName);
                attr.Value = value;
                node.Attributes.SetNamedItem(attr);
                return attr;
            }
            catch (Exception err)
            {
                string desc = err.Message;
                return null;
            }
        }

        private void clear()
        {
            dt3.Clear();
            dgv2.DataSource = dt3;
            dt2.Clear();
            dgv1.DataSource = dt2;
        }

        private void deleteitgroup(String id)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNodeList nodelist = doc.SelectNodes("//Courses/ITCourse/InstructorID");
            for (int i = 0; i < nodelist.Count; i++)
            {
                if (nodelist[i].InnerText == id)
                {
                    nodelist[i].ParentNode.RemoveChild(nodelist[i]);
                }
            }
            doc.Save("Course.xml");
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            int temp;
            if (txtChange.Text.Trim() != String.Empty)
            {
                if (int.TryParse(txtChange.Text, out temp))
                {
                    int.TryParse(txtChange.Text, out groups);
                    if (groups >= 0)
                    {
                        temp = groups;
                        temp = temp - searchRemain();
                        if (temp >= 0)
                        {
                            lbltip3.Hide();
                            remain = groups;
                            remain = remain - searchRemain();
                            lblRemain.Text = remain.ToString();
                            XmlDocument doc = new XmlDocument();
                            doc.Load("Course.xml");
                            string path = "//ITCourse";
                            XmlNode node = doc.SelectSingleNode(path);
                            node.Attributes[0].Value = groups.ToString();
                            node.Attributes[1].Value = remain.ToString();
                            doc.Save("Course.xml");
                            clear();
                            txtChange.Text = groups.ToString();
                        }
                        else
                        {
                            MessageBox.Show("Please input a vaild number!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please input a vaild number!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    }
                }
                else
                {
                    MessageBox.Show("Please input a real number!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                lbltip3.Show();
                MessageBox.Show("You have not input the total group!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            XmlDocument doc2 = new XmlDocument();
            doc2.Load("Course.xml");
            string pathTotal = "//Courses/ITCourse";
            XmlNode node2 = doc2.SelectSingleNode(pathTotal);
            label5.Text = node2.Attributes[0].Value;

        }

       


        private int searchRemain()
        {
            int sum=0;
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            XmlNodeList nodelist = doc.SelectNodes("//Courses/ITCourse/InstructorID");
            if (nodelist == null)
            {
                return 0;
            }
            else
            {
                for(int i = 0; i < nodelist.Count; i++)
                {
                    int add;
                    int.TryParse(nodelist[i].Attributes[1].Value, out add);
                    sum = sum + add;
                }
                return sum;
            }

                 
        }

        private void deleteIT(String id,int decrease)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("Course.xml");
            String path = "//Courses/CourseInfo/Course";
            XmlNodeList nodelist = doc.SelectNodes(path);
            for (int i = 0; i < nodelist.Count; i++)
            {
                if (nodelist[i].ChildNodes[6].InnerText == id&&nodelist[i].ChildNodes[7].InnerText=="IT")
                {
                    nodelist[i].ParentNode.RemoveChild(nodelist[i]);
                }
            }
            doc.Save("Course.xml");

            XmlDocument xml = new XmlDocument();
            xml.Load("Course.xml");         //load the Course.xml
            String path1 = "//Courses/CourseInfo[@Number]";     //find the attribute of course number
            XmlNode node1 = xml.SelectSingleNode(path1);
            int temp;
            int.TryParse(node1.Attributes[0].Value, out temp);      //change the type from string to integer
            temp=temp-decrease;         //add 1 course
            node1.Attributes[0].Value = temp.ToString();        //cover the old value
            xml.Save("Course.xml");
        }

       
        private void btnShowAll_Click(object sender, EventArgs e)
        {
            clear();
            XmlDocument doccourse = new XmlDocument();
            XmlDocument docstaff = new XmlDocument();
            doccourse.Load("Course.xml");
            docstaff.Load("Staff.xml");
            string pathcourse = "//ITCourse/InstructorID";
            string pathstaff = "//Instructors/InstructorID";
            XmlNodeList course = doccourse.SelectNodes(pathcourse);
            XmlNodeList staff = docstaff.SelectNodes(pathstaff);
            for(int i = 0; i < course.Count; i++)
            {
                dt2.Rows.Add(course[i].Attributes[0].Value, course[i].Attributes[1].Value);
                for(int j = 0; j < staff.Count; j++)
                {
                    if (course[i].InnerText == staff[j].InnerText)
                    {
                        dt3.Rows.Add(staff[j].Attributes[0].Value, staff[j].Attributes[1].Value);
                        break;
                    }
                }
            }
            dgv1.DataSource = dt2;
            dgv2.DataSource = dt3;
        }

        private void courseInformationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormCourseinformation form = new FormCourseinformation();
            form.Show();
            this.Hide();
        }

        private void tAArrangementToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Form1 form = new Form1();
            form.Show();
            this.Hide();
        }

        private void instructorInfomationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FormAddinstructor form = new FormAddinstructor();
            form.Show();
            this.Hide();
        }

        private void courseTimeToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void txtITGroups_MouseHover(object sender, EventArgs e)
        {
            lbltip1.Show();
            lbltip2.Show();
        }
    



        private void pictureBox1_Click(object sender, EventArgs e)
        {
            FormHeadPixel headPixel = new FormHeadPixel();
            headPixel.Show();
            this.Close();
        }

        private void lblRemain_Click(object sender, EventArgs e)
        {

        }
        
    }
}
